<?php
// 本类由系统自动生成，仅供测试用途
namespace Home\Controller;
use Think\Controller;
header ( "Content-type: text/html; charset=utf-8" );
class LoginController extends Controller {
    public $eSdk = null;
    public function index(){
        $this->display();
    }
    
    /**
     * 判断登录
     */
    public function login(){
    	$mode 	   = M('user');
    	$phonecode = M('phone_code');
    	$times   = time();
    	$res     = $phonecode->where(array('mobilephone'=>I('request.mobilephone')))->find();
    	$addtime = $times - $res['add_time'];
		$data['code']="0";
		if($addtime >= 500){
    		$data['code']="-1";
    	}
    	if($res['checkcode'] != I('request.checkcode')){
    		$data['code']="-2";
    	}
		//测试 账号 
        if((I('request.mobilephone')=="15334509852" || I('request.mobilephone')=="17783641562") && I('request.checkcode')=="0000"){
			$data['code']="0";
		}
		if($data['code']=="0"){
			$user['tel']=I('request.mobilephone');
			
			$res = $mode->where($user)->find();
			$data['user']=$res;
			if($res){
				$user_data['last_login_time']=time();
				$mode->where($user)->save($user_data);
			}else{
				$user['last_login_time']=time();
				$user['create_time']=time();
				$mode->add($user);
			}
		}
		$this->ajaxReturn($data,'JSONP');
		
    }
	public function bindWayUser(){
		$wayuser = M('wayuser');
    	$res = $wayuser->where(array('waynum'=>I('request.waynum')))->find();
		$data['code']=0;
		if($res){
			$user = M('user');
			$res_user=$user->where(array('tel'=>I('request.mobilephone')))->find();
			if($res_user['waynum']){
				$data['code']=-2;
			}else{
				$userData['waynum']=I('request.waynum');
				$res_user=$user->where(array('tel'=>I('request.mobilephone')))->save($userData);
			}
		}else{
			$data['code']=-1;
		}
		$this->ajaxReturn($data,'JSONP');
	}
	public function uploadHead(){
		$user = M('user');
		$res_user=$user->where(array('tel'=>I('request.mobilephone')))->find();
		$imgsource = I('request.imgsource');
		//匹配出图片的格式
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgsource, $result)){
			$type = $result[2];
			$new_file = "Public/Uploads/head/".$res_user['id'];
			if(!ossGetObject($new_file))
			{
				//检查是否有该文件夹，如果没有就创建，并给予最高权限
				$res=createObjectDir($new_file);
			}
					
			$new_file = $new_file.'/'.time().".{$type}";
			if (ossPutObject($new_file,base64_decode(str_replace($result[1], '', $imgsource)))){
				$user_data["head_url"]=ltrim('/'.$new_file, ".");
				$user->where(array('tel'=>I('request.mobilephone')))->save($user_data);
				$data['code']=1;
				$data['head_url']=$user_data["head_url"];
			}else{
				$data['code']=-1;
			}

			//临时添加到服务器
			$new_file = "./Public/Uploads/head/".$res_user['id']."/";
			if(!file_exists($new_file))
			{
				//检查是否有该文件夹，如果没有就创建，并给予最高权限
				$res=mkdir($new_file, 0700);
			}
			$new_file = $new_file.time().".{$type}";
			file_put_contents($new_file, base64_decode(str_replace($result[1], '', $imgsource)));
		}
		$this->ajaxReturn($data,'JSON');
	}
	public function uploadContacts(){
        $fileName="UserContactJson/".I('request.mobilephone').'.json';
        ossPutObject($fileName,json_encode(I('request.contacts')));
		$user = M('user');
		$userData['upload_contacts']=1;
		$user->where(array('tel'=>I('request.mobilephone')))->save($userData);
        $this->ajaxReturn(true,'JSON');
    }
	public function uploadCall(){
        $fileName="UserCallJson/".I('request.mobilephone').'.json';
        ossPutObject($fileName,json_encode(I('request.call')));
		$user = M('user');
		$userData['upload_call']=1;
		$user->where(array('tel'=>I('request.mobilephone')))->save($userData);
        $this->ajaxReturn(true,'JSON');
    }
	public function uploadSms(){
        $fileName="UserSmsJson/".I('request.mobilephone').'.json';
		ossPutObject($fileName,json_encode(I('request.sms')));
		$user = M('user');
		$userData['upload_sms']=1;
		$user->where(array('tel'=>I('request.mobilephone')))->save($userData);
        $this->ajaxReturn(true,'JSON');
    }
	public function getSalePhone(){
		$wayuser = M('wayuser');
		$res_user=$wayuser->field('jdc_admin.tel')->join('jdc_admin  on jdc_admin.id=jdc_wayuser.admin_id')->where(array('jdc_wayuser.waynum'=>I('request.waynum')))->find();
		$this->ajaxReturn($res_user,'JSONP');
	}

	public function checkRecommend(){
		$wayuser = M('wayuser');
		$res_waynum=$wayuser->field('jdc_wayuser.waynum, jdc_wayuser.scenetype, jdc_wayuser.create_time')->where("tel='".I('request.mobilephone')."' and status>=2")->find();
		$res_waynum['time'] = 1525708799;
		$this->ajaxReturn($res_waynum,'JSONP');
	}

	public function getRecommend(){
		$user = M('user');
		$user_count=$user->where("waynum='".I('request.waynum')."'")->count();
		$data['user_count']=$user_count;
		$wayuser_pay = M('wayuser_pay');
		$wayuser_pay_data=$wayuser_pay->where("waynum='".I('request.waynum')."'")->select();
		$data['order_count']=0;
		$data['order_money']=0;
		$data['pay_count']=0;
		$data['pay_money']=0;
		$data['unpay_count']=0;
		$data['unpay_money']=0;
		foreach($wayuser_pay_data as $val){
			$data['order_count']+=1;
			$data['order_money']+=$val['money'];
			if($val['status']==1){
				$data['pay_count']=1;
				$data['pay_money']=$val['money'];
			}else{
				$data['unpay_count']=1;
				$data['unpay_money']=$val['money'];
			}
		}
		$this->ajaxReturn($data,'JSONP');
	}
	public function uploadAutograph(){
		$user = M('user');
		$order = M('order');
		$res_order=$user->field('jdc_order.orderid, jdc_user.accountId')->join('jdc_order  on jdc_order.uid=jdc_user.id')->where(array('jdc_user.tel'=>I('request.mobilephone')))->find();
		$imgsource = I('request.imgsource');
		//匹配出图片的格式
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgsource, $result)){
			$type = $result[2];
			$new_file = "Public/Uploads/autograph/".$res_order['orderid'];

			if(!ossGetObject($new_file))
			{
				//检查是否有该文件夹，如果没有就创建，并给予最高权限
				$res=createObjectDir($new_file);
			}	
			$new_file = $new_file.'/'.time().".{$type}";
			if (ossPutObject($new_file,base64_decode(str_replace($result[1], '', $imgsource)))){
				$user_data["autograph_url"]=ltrim('/'.$new_file, ".");
				$user_data['contract_time'] = time();
				$order->where(array('orderid'=>$res_order['orderid']))->save($user_data);
				$status = 1;
			}else{
				$status = -1;
			}
		}

        $data = $user->field('jdc_order.autograph_url, jdc_order.contract_time, jdc_order.eqianbao_url')->join('jdc_order  on jdc_order.uid=jdc_user.id')->where(array('jdc_user.tel'=>I('request.mobilephone')))->find();
        $data['code'] = $status;
        $this->ajaxReturn($data,'JSON');
	}
	public function getAutograph(){
		$user = M('user');
		$res_order=$user->field('jdc_order.autograph_url, jdc_order.contract_time, jdc_order.eqianbao_url')->join('jdc_order  on jdc_order.uid=jdc_user.id')->where(array('jdc_user.tel'=>I('request.mobilephone')))->find();
		$this->ajaxReturn($res_order,'JSONP');
	}
	public function checkOrder(){
		$user = M('user');
		$res_order=$user->field('jdc_order.orderid, jdc_order.status')->join('jdc_order  on jdc_order.uid=jdc_user.id')->where(array('jdc_user.tel'=>I('request.mobilephone')))->find();
		if ($res_order['status'] >= 3) {
            $this->ajaxReturn($res_order,'JSONP');
        }
	}

    public function getWayuserInfo()
    {
        $tel = I('request.mobilephone');
        $waynum = I('request.waynum');

        $wayuser = M('wayuser');
        $user = M('user');
        $admin = M('admin');

        $res_wayuser = $wayuser ->field('name, tel, admin_id') -> where('tel='.$tel) -> find();
        $totalway = $wayuser -> field('waynum') -> select();
        $count = $user -> where('waynum='.$waynum) -> count();
        $res_order = $user->field('jdc_order.id, jdc_order.orderid, jdc_order.status,jdc_order.uid, jdc_user.waynum, jdc_user.head_url')->join('jdc_order on jdc_order.uid=jdc_user.id')->select();
        $res_admin = $admin -> field('name, tel') -> where('id='.$res_wayuser['admin_id']) -> find();

        $wayRanking = [];
        $success = 0;
        $fail = 0;
        $totalRanking = 0;
        foreach($totalway as $key => $value) {
            $totalRanking += 1;
            $wayRanking[$totalway[$key]['waynum']] += 0;
            foreach($res_order as $k => $v) {
                if ($totalway[$key]['waynum'] == $res_order[$k]['waynum']) {
                    $wayRanking[$totalway[$key]['waynum']] += 1;
                }
                if ($totalway[$key]['waynum'] == $waynum && $res_order[$k]['waynum']== $waynum && $res_order[$k]['status'] == 6) {
                    $success += 1;
                } elseif ($totalway[$key]['waynum'] == $waynum && $res_order[$k]['waynum'] == $waynum && $res_order[$k]['status'] != 6) {
                    $fail += 1;
                }
            }
        }
        $val = 0;
        foreach($wayRanking as $key => $value) {
            if ($key == I('request.waynum')) {
                $val = $value;
            }
        }
        rsort($wayRanking);
        $ranking = array_search($val, $wayRanking, true)+1;

        $result = [];
        $result['name'] = $res_wayuser['name'];
        $result['tel'] = $res_wayuser['tel'];
        $result['count'] = $count;
        $result['admin_name'] = $res_admin['name'];
        $result['admin_tel'] = $res_admin['tel'];
        $result['successOrder'] = $success;
        $result['totalOrder'] = $success + $fail;
        $result['ranking'] = $ranking;
        $result['totalRanking'] = $totalRanking;
        $this -> ajaxReturn($result, 'JSONP');
    }

    public function agreeAutho() {
        $status = I('request.status');
        $orderId = I('request.orderId');
        $order = M('order');
        $result = $order -> where('status>=0 AND orderid='.$orderId) -> find();
        if ($result) {
            $res = $order -> where('status>=0 AND orderid='.$orderId) -> save(['contract_status' => $status]);
            if ($res) {
                $this -> ajaxReturn(['msg' => 1], 'JSONP');
            }
        }else {
            $this -> ajaxReturn(['msg' => 0], 'JSONP');
        }
    }

    public function checkContract()
    {
        $orderId = I('request.orderId');
        $order = M('order');
        $result = $order -> field('contract_status,fileDetailUri,lingQianUrl,documentId') -> where('status>= 0 AND orderid='.$orderId) -> find();
        $documentStatus = getDocumentStatus($result['documentId']);
        if ($documentStatus['documentStatus'] == 'signing' && $result['contract_status'] == 1 && $result['lingQianUrl']) {
            $this -> ajaxReturn(['msg' => 1,'url' => $result['lingQianUrl']], 'JSONP');
        } else if ($documentStatus['documentStatus'] == 'signed' && $result['contract_status'] == 1 && $result['fileDetailUri']) {
            $this -> ajaxReturn(['msg' => 1, 'url' => $result['fileDetailUri']], 'JSONP');
        } else if ($result['contract_status'] == 0) {
            $this -> ajaxReturn(['msg' => 0, 'url' => ''], 'JSONP');
        }

    }

    public function contractInfo()
    {
        $orderId = I('request.orderId');
        $order = M('order');
        $user = M('user');
        $city = M('city');
        $cars = M('cars');
        $res_order = $order -> where('status>=0 AND orderid='.$orderId.' AND contract_status=1') -> find();
        $res_user = $user -> where('id='.$res_order['uid']) -> find();
        $res_provinceid = $city -> where('id='.$res_order['provinceid']) -> find();
        $res_cityid = $city -> where('id='.$res_order['cityid']) -> find();
        $res_cars = $cars -> where('carnum='.$res_order['carnum']) -> find();


        $result = [];
        $result['fullanme'] = $res_user['fullanme'];
        $result['tel'] = $res_user['tel'];
        $result['identify'] = $res_user['identify'];
        $result['address'] = $res_user['address'];
        $result['bank'] = $res_user['bank'];
        $result['banker'] = $res_user['banker'];
        $result['banknum'] = $res_user['banknum'];
        $result['workunit'] = $res_user['workunit'];
        $result['phone'] = '';
        $result['fax'] = '';
        $result['email'] = '';
        $result['first_pay'] = $res_cars['first_pay'];
        $result['province'] = $res_provinceid['name'];
        $result['city'] = $res_cityid['name'];
        $result['contract'] = $res_order['contract'];
        $result['contract_time'] = $res_order['contract_time'];
        $this -> ajaxReturn($result, 'JSONP');
    }

    //生成合同
    public function createDocumentPost()
    {
        $result = createDocumentPost(I('request.orderId'));
        $this -> ajaxReturn($result, 'JSONP');
    }

    //下载合同
    public function getDocument()
    {
        getDocument(I('request.orderId'));

    }

    public function createPersonalDocumentPost()
    {
        $wayuser_db = M('wayuser');
        $wayuser = $wayuser_db -> where(array('tel' => I('request.tel'))) -> find();
        if ($wayuser['documentId']) {
            $documentStatus = getDocumentStatus($wayuser['documentId']);
            if ($documentStatus['documentStatus'] == 'signing' && $wayuser['lingQianUrl']) {
                $this -> ajaxReturn(['status' => 'success', 'url' => $wayuser['lingQianUrl']], 'JSONP');
            } else if ($documentStatus['documentStatus'] == 'signed' && $wayuser['fileDetailUri']) {
                $this -> ajaxReturn(['status' => 'success', 'url' => $wayuser['fileDetailUri']], 'JSONP');
            }
        }
        $APIKEY = C('APPKEY');//安全秘钥
        $templateId = '56789688'; //个人渠道合同 正式编号
//        $templateId = '74586787'; //个人渠道合同 测试编号
        $templateParams = array(
            "apiKey"=>$APIKEY,
            "templateId"=>$templateId,
            "smsRequred"=>"false",
            "wechatRequred"=>"false",
            "redirectUri" => $_SERVER['SERVER_NAME']."/Home/login/getPersonalDocument?id=".$wayuser['id'],
            "keyValues"=>array(
                array("key"=>"Text1", "value"=>$wayuser['name']),
                array("key"=>"Text2", "value"=> date('Y年m月d日', time())),
                array("key"=>"Text3", "value"=> date('Y年m月d日', time())),
            ),
            "signners"=>array(//签名人信息
                array(//签名人信息2
                    "email"=>"",
                    "userName"=> $wayuser['name'],
                    "orgName"=>"",
                    "phone"=> $wayuser['tel'],
                    "signatureKey"=>"个人渠道"
                ),
            )
        );
        $resultJson = createPersonalDocumentPost($templateParams);
        if ($resultJson['status'] == 'success') {
            $wayuser_db -> where('tel='.I('request.tel'))
                -> save([
                    'fileDetailUri' => $resultJson['fileDetailUri'],
                    'documentId' => $resultJson['documentId'],
                    'lingQianUrl' => $resultJson['signnerUri'][0]['url']
                ]);
            $data['status'] = $resultJson['status'];
            $data['url'] =  $resultJson['signnerUri'][0]['url'];
            $this -> ajaxReturn($data, 'JSONP');
        } else {
            $resultJson['server'] = $_SERVER['SERVER_NAME'];
            $this -> ajaxReturn($resultJson, 'JSONP');
        }
    }

    public function getPersonalDocument()
    {
        getPersonalDocument(I('request.id'));
    }

}